package com.becca.cake.controller.system;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.becca.cake.core.common.BaseAction;
import com.becca.cake.model.system.AdminDO;
import com.becca.cake.service.system.IUserLoginService;
import com.becca.cake.util.JsonUtil;
import com.becca.cake.util.PMSConstants;
import com.becca.cake.util.StringUtil;

/**
 * 系统用户登录
 * @author hejinguo
 * @version $Id: UserLoginAction.java, v 0.1 2013-12-2 下午04:52:35
 */
@Controller
@RequestMapping("/systemUser")
public class UserLoginAction extends BaseAction {
    private final static Log  logger = LogFactory.getLog(UserLoginAction.class);
    @Autowired
    private IUserLoginService iUserLoginService;

    /**
     * 用户登录数据校验
     * @param request
     * @param uname
     * @param password
     * @param validateNumber
     * @return
     */
    @RequestMapping(value = { "/loginUserCheck" }, method = { RequestMethod.POST }, consumes = { "application/json" }, produces = { "application/json" })
    public @ResponseBody
    String loginUserCheck(HttpServletRequest request, @RequestBody AdminDO adminDO) {
        if (adminDO == null) {
            return JsonUtil.returnJsonSpecialUnSuccess("用户名、密码、验证码不能为空!");
        }
        //空校验
        if (StringUtil.isEmpty(adminDO.getName()) || StringUtil.isEmpty(adminDO.getPass())
            || StringUtil.isEmpty(adminDO.getValidateNumber())) {
            return JsonUtil.returnJsonSpecialUnSuccess("用户名、密码、验证码不能为空!");
        }
        //验证码校验
        String validateCode = String.valueOf(request.getSession().getAttribute("simpleCaptcha"));
        if (StringUtil.isEmpty(validateCode)) {
            return JsonUtil.returnJsonSpecialUnSuccess("验证码为空，请刷新再登录!");
        }
        if (!adminDO.getValidateNumber().trim().toUpperCase().equals(validateCode)) {
            return JsonUtil.returnJsonSpecialUnSuccess("验证码输入有误!请重新输入...");
        }
        //查询用户
        try {
            AdminDO priAdminDO = this.iUserLoginService.login(adminDO.getName(), adminDO.getPass());
            if (priAdminDO == null) {
                return JsonUtil.returnJsonSpecialUnSuccess("登录名不存在或密码有误!请重新输入...");
            }
        } catch (Exception e) {
            logger.error("登录异常!", e);
            return JsonUtil.returnJsonSpecialUnSuccess("登录异常!");
        }
        return JsonUtil.returnJsonSuccess("验证成功!");
    }

    /**
     * 系统用户登录 
     * @author hejinguo
     * @param request
     * @param uname 用户名
     * @param password  密码
     * @param validateNumber  验证码
     * @return
     * @throws Exception 
     * method 不写表示支出get和post请求。也可写表示支出某一种请求
     */
    @RequestMapping(value = "/loginUser", method = { RequestMethod.POST, RequestMethod.GET })
    public ModelAndView loginUser(HttpServletRequest request,
                                  @RequestParam(value = "uname", required = false) String uname,
                                  @RequestParam(value = "pass", required = false) String password,
                                  @RequestParam(value = "validateNumber", required = false) String validateNumber) {
        //查询用户
        AdminDO adminDO = (AdminDO) this.getSession().getAttribute(PMSConstants.LOGIN_USER);
        if (adminDO != null) {
            return new ModelAndView("index/index");
        }
        try {
            AdminDO priAdminDO = this.iUserLoginService.login(uname, password);
            if (priAdminDO == null) {
                return new ModelAndView(new RedirectView("../login.jsp"));
            }
            //登录成功
            this.getSession().setAttribute(PMSConstants.LOGIN_USER, priAdminDO);
            this.getSession().removeAttribute("info");
            return new ModelAndView("index/index");
        } catch (Exception e) {
            logger.error("登录异常!", e);
            return new ModelAndView(new RedirectView("../login.jsp"));
        }
    }

    /**
     * 系统退出
     * @author hejinguo
     * @param request
     * @return
     */
    @RequestMapping(value = "/loginout", method = RequestMethod.POST)
    public @ResponseBody
    String loginout(HttpServletRequest request) {
        request.getSession().invalidate();
        return JsonUtil.returnJsonSuccess("操作成功!");
    }

    /**
     * 修改密码
     * @author hejinguo
     * @param request
     * @param oldPass 旧密码
     * @param newPass 新密码
     * @param pass  确认密码
     * @return
     */
    @RequestMapping(value = "/updatePassWord", method = RequestMethod.POST)
    public @ResponseBody
    String updatePassWord(HttpServletRequest request,
                          @RequestParam(value = "uname", required = false) String uname,
                          @RequestParam(value = "oldPass", required = false) String oldPass,
                          @RequestParam(value = "newPass", required = false) String newPass,
                          @RequestParam(value = "pass", required = false) String pass) {
        if (!newPass.equals(pass)) {
            return JsonUtil.returnJsonUnSuccess("新密码和确认密码必须相同!");
        }
        if (this.getUserSeesion() == null) {
            return JsonUtil.returnJsonUnSuccess("用户未登录,请重新登录!");
        }
        try {
            this.iUserLoginService.updatePassWord(this.getUserSeesion(), oldPass, newPass);
            return JsonUtil.returnJsonSuccess("修改成功,请重新登录!");
        } catch (Exception e) {
            logger.error("修改密码失败!", e);
        }
        return JsonUtil.returnJsonUnSuccess("修改密码失败!");
    }

    /**
     * 返回登录错误信息
     * @author hejinguo
     * @param request
     * @param message 提示消息
     * @return
     */
    public ModelAndView returnAndView(HttpServletRequest request, String message) {
        request.getSession().setAttribute("info", message);
        return new ModelAndView(new RedirectView("../login.jsp"));
    }
}
